// pages/youXuan/tabBar/type/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIdx:1,
    tabList:[
      {name:'满29减4',id:1},
      {name:'每日上新',id:2},
      {name:'新鲜蔬菜',id:3},
      {name:'时令水果',id:4},
      {name:'肉禽蛋品',id:5},
      {name:'海鲜水产',id:6},
      {name:'酒水饮料',id:7},
      {name:'休闲食品',id:8}
    ],
    tabIndex:1,
    list:wx.getStorageSync('yx-shoplist')||[],//公共数据
    total:20,
    more:false,
    shopcartList:[]//购物车数据
  },
  addFunc(event){
    //加入购物车
    var dataset=event.currentTarget.dataset
    let item=this.data.list[dataset.index]
    let list=this.data.list
    if(dataset.flag){
      item.num++
    }else{
      if(item.num>0){
        item.num--
      }
    }
    list[dataset.index]=item
    this.setData({
      list
    })
    wx.setStorageSync('yx-shoplist',list)
    this.setShopCart(dataset.index)
  },
  setShopCart(index){
    let list=wx.getStorageSync('yx-shopcart')
    let item=this.data.list[index]
    if(list&&list.length>0){
      let bol=false,idx
      list.forEach((i,index)=>{
        if(i.id==item.id){
          if(item.num==0){
            idx=index
          }else{
            i.num=item.num
          }
          bol=true
        }
        if((index+1)==list.length){
          if(!bol){
            list.push(item)
          }else{
            if(idx>=0){
              list.splice(idx,1)
            }
          }
        }
      })
    }else{
      list=[item]
    }
    wx.setStorageSync('yx-shopcart',list) 
    this.getShopCart()
  },
  getShopCart(){
    let list=wx.getStorageSync('yx-shopcart')||[]
    let shoplist=wx.getStorageSync('yx-shoplist')||[]
    this.setData({
      shopcartList:list,
      list:shoplist
    })
  },
  changeTab(event){
    //切换tab
    var dataset=event.currentTarget.dataset
    this.setData({
      tabIndex:dataset.id
    })
  },
  getMore(){
    //加载更多
    if(this.data.total>this.data.list.length&&!this.data.more){
      this.setData({
        more:true
      })
      setTimeout(()=>{
        let arr=[]
        let data=this.data.list.concat(arr)
        this.setData({
          list:data,
          more:false
        })
      },1000)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getShopCart()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})